package com.example.remoteclient;

import sensormodule.ISensorListener;
import sensormodule.SensorModule;
import networkmodule.TCPClient;
import networkmodule.TCPClient.INetworkMessageListener;
import networkmodule.message.CommandMessage;
import networkmodule.message.MessageFactory;
import networkmodule.message.SensorMessage;
import Utils.Logger;
import Utils.Logger.ILoggable;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements INetworkMessageListener, ILoggable, ISensorListener {
	private Logger _logger;
	public TCPClient _clientTCP;
	private SensorModule _sensoManager;
	private Handler _handler;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// Init logger
		_logger = new Logger();
		_logger.addTarget(this);
		_sensoManager = new SensorModule(this, this);
		
		_handler = new Handler(Looper.getMainLooper()) {
			@Override
			public void handleMessage(Message msg) {
				float[] data = (float[])msg.obj;
				
				((EditText)findViewById(R.id.tfX)).setText(Float.toString(data[3]));
				((EditText)findViewById(R.id.tfY)).setText(Float.toString(data[4]));
				((EditText)findViewById(R.id.tfZ)).setText(Float.toString(data[5]));
			}
		};
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void onConnectClick(View view)
	{
		try
		{
			String ip = ((EditText)findViewById(R.id.tfIp)).getText().toString();
			int port = Integer.parseInt(((EditText)findViewById(R.id.tfPort)).getText().toString()) ;
			(new ConnectTask()).execute(ip, port, this);
			_logger.pushMessage("Connecting to server");
		} catch (Exception ex) {
		}
	}
	
	public void onStartClick(View view)
	{
		try
		{
			// Send test message to server
			//CommandMessage cmdMsg = MessageFactory.createCommandSendMessage("Hello server again!");
			//_clientTCP.sendMessage(cmdMsg);
			_logger.pushMessage("Sended!");
			_sensoManager.startSensor();
			
			
		} catch (Exception ex) {
		}
	}
	
	public void onCaptureClick(View view)
	{
		try
		{
			// Send test message to server
			CommandMessage cmdMsg = MessageFactory.createCaptureOrientation();
			_clientTCP.sendMessage(cmdMsg);
			_logger.pushMessage("Capture command sended!");
			
			
		} catch (Exception ex) {
		}
	}
	
	public void onFilterClick(View view)
	{
		try
		{
			// Send test message to server
			CommandMessage cmdMsg = MessageFactory.createFilterMode();
			_clientTCP.sendMessage(cmdMsg);
			_logger.pushMessage("Capture command sended!");
			
			
		} catch (Exception ex) {
		}
	}
	
	@Override
	public void messageReceived(String message) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void logReceived(String message) {
		// This method be used for logger
		// Set message
		String currentText = ((TextView)findViewById(R.id.tvLog)).getText().toString();
		((TextView)findViewById(R.id.tvLog)).setText(currentText+"\n"+message);
	}
	
	/**
	 * Class AsynTask for 
	 */
	public class ConnectTask extends AsyncTask<Object, String, TCPClient>
	{
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
			
			_logger.pushMessage("Receipt message");
		}

		@Override
		protected TCPClient doInBackground(Object... params) {
			String ip = (String)params[0];
			int port = (int)params[1];
			MainActivity main = (MainActivity)params[2];
			TCPClient client = new TCPClient(ip, port, new INetworkMessageListener() {
				
				@Override
				public void messageReceived(String message) {
					publishProgress(message);
				}
			});

			main._clientTCP = client;
			client.run();
			return client;
		}
	}

	@Override
	public void onReceiptSensorData(float[] data) {
		// TODO Auto-generated method stub
		if (data == null)
			return;
		SensorMessage sensorMsg = MessageFactory.createSensorMessage();
		sensorMsg.getAccels().put("x", data[0]);
		sensorMsg.getAccels().put("y", data[1]);
		sensorMsg.getAccels().put("z", data[2]);
		sensorMsg.getMagOrientation().put("x", data[3]);
		sensorMsg.getMagOrientation().put("y", data[4]);
		sensorMsg.getMagOrientation().put("z", data[5]);
		Message message = _handler.obtainMessage(1, data);
		_handler.sendMessage(message);
		_clientTCP.sendMessage(sensorMsg);
		//((EditText)findViewById(R.id.tfIp)).setText(Float.toString(data[3]));
	}
}


